package cn.org.spring.wechar.consumer;

import cn.org.spring.wechar.bean.message.template.TemplateDate;
import cn.org.spring.wechar.bean.message.template.TemplateMessage;
import cn.org.spring.wechar.service.TemplateService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 消费者
 * Created with IntelliJ IDEA.
 * User:  wanghongjie
 * Date:  2020/11/6 - 23:22
 * <p>
 * Description:
 *
 * @blame Android Team
 */
@Component
@Slf4j
public class MqConsumer {

    @Resource
    private TemplateService templateService;

    @RabbitListener(bindings = {
            @QueueBinding(value = @Queue(value = "${we-char.we-char-queue}", durable = "true"),
                    exchange = @Exchange(value = "${we-char.we-char-exchange}"),
                    key = "${we-char.direct-key}")
    })
    @RabbitHandler
    public void processTopicMsg(Message massage) throws IOException {
        String msg = new String(massage.getBody(), StandardCharsets.UTF_8);
        log.info("received direct message send [{}] ", msg);
        JSONObject jsonObject = JSONObject.parseObject(msg);
        TemplateMessage message = TemplateMessage.builder().touser(jsonObject.getString("toUser"))
                .template_id(jsonObject.getString("templateId"))
                .data(TemplateDate.of(jsonObject.getString("data").split("##"))).build();
        log.info("send message is [{}]", message.toJson());
        String status = templateService.send(message.toJson());
        log.info("send message status is {}", status);
    }
}